﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      Role Assignment Page
// Created By:     Miles Chen (milesch@wicresoft.com)
// Created Date:   2011-2-26
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASB.CC.Business.CIS;
using ASBCC.Business;
using ASBCC.Database.EntityFramework;

namespace ASB.CC.Web.Admin
{
    public partial class RoleAssignment : EntityPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!GetModuleName().All(p => Enum.GetNames(typeof(SystemModule)).Contains(p)))
                throw new ApplicationException("QueryString['sys']格式不正确");
        }

        protected string[] GetModuleName()
        {
            var sys = RoleAssignmentHelper.CheckURL(this.Request.QueryString["sys"].Split(','), (User as CSPrincipal).CIL);
            if (sys == null)
                throw new ApplicationException("QueryString['sys']不能为空");
            //if (sys[0] == "Access Denied")
            //{
            //    GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.Admin, "用户:"+this.User.Identity.Name+" 试图越权访问RoleAssignment");
            //    throw new System.Security.Authentication.AuthenticationException("Access Denied");

            //}
            return sys;
        }

        protected string GetModuleText()
        {
            var sys = GetModuleName();
            if (sys.Length == 1)
                return sys.First();
            else
                return "All";
        }
        protected bool IsAdmin(object dataItem)
        {
            var employee = dataItem as Employee;
            var sys = GetModuleName();
            return employee.Roles.Any(p => !p.Disabled && p.IsAdmin && sys.Contains(p.BelongsTo));
        }

        protected IEnumerable GetRoles(object dataItem)
        {
            var employee = dataItem as Employee;
            var sys = GetModuleName();
            return employee.Roles.Where(p => !p.Disabled && sys.Contains(p.BelongsTo) && p.Description != "+pcat+" && p.Description != "+country+").OrderBy(p => p.BelongsTo).ThenBy(p => p.IsAdmin);
        }

        protected string GetRoleStyle(object dataItem)
        {
            return (bool)dataItem ? "role-admin" : "";
        }

        protected override EntityDataSource EntitySource
        {
            get { return edsMain; }
        }

        protected override Panel GridPanel
        {
            get
            {
                return gridPanel;
            }
        }
       
        protected override GridView EntityGrid
        {
            get { return gvMain; }
        }

        protected override DetailsView EntityDetails
        {
            get { return dvMain; }
        }

        protected override TextBox EntitySearchTxt
        {
            get { return txtSearch; }
        }

        protected override Button EntityAddBtn
        {
            get { return btnAdd; }
        }

        protected override Button EntityClearBtn
        {
            get { return btnClear; }
        }

        protected override Button EntitySearchBtn
        {
            get { return btnSearch; }
        }

        protected override void OnEntityDisabling(int entityKey)
        {
            // do nothing
        }


        protected override void OnEntityInserting(EntityDataSourceChangingEventArgs e)
        {
            e.Cancel = true;
            InsertEmployee(e);
            var employee = e.Entity as Employee;
            string sys = GetModuleText().ToString();
            string chooseRolesStr;
            string roles;
            if (Request.Form["ChooseRoles"] == null)
            {
                chooseRolesStr = string.Empty;
                roles = "";
            }
            else
            {
                chooseRolesStr = Request.Form["ChooseRoles"].ToString();
                roles = LogInfoHelper.GetRolesAll(employee.NameEN, chooseRolesStr).ToString();
            }
            var employeeNO = RoleAssignmentHelper.getEmployeeNo(employee.NameEN);
            var isAdmin = LogInfoHelper.GetIsAdminAll(employeeNO, sys);
            if (GetModuleText().ToString() == "CCD")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CCD, "RoleAssignment inserted. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "CCO")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CCO, "RoleAssignment inserted. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "All")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.Admin, "RoleAssignment inserted. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "ACR")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.ACR, "RoleAssignment inserted. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "EZVisit")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.EZVisit, "RoleAssignment inserted. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }


            Entity_Changed(null, null);
        }

        protected override void OnEntityUpdating(EntityDataSourceChangingEventArgs e)
        {
            e.Cancel = true;
            UpdateEmployee(e);
            var employee = e.Entity as Employee;
            string sys = GetModuleText().ToString();
            string chooseRolesStr;
            string roles;
            if (Request.Form["ChooseRoles"] == null)
            {
                chooseRolesStr = string.Empty;
                roles = "";
            }
            else
            {
                chooseRolesStr = Request.Form["ChooseRoles"].ToString();
                roles = LogInfoHelper.GetRolesAll(employee.NameEN, chooseRolesStr).ToString();
            }

            var employeeNO = RoleAssignmentHelper.getEmployeeNo(employee.NameEN);
            var isAdmin = LogInfoHelper.GetIsAdminAll(employeeNO, sys);

            if (GetModuleText().ToString() == "CCD")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CCD, "RoleAssignment updated. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "CCO")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CCO, "RoleAssignment updated. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "All")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.Admin, "RoleAssignment updated. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "ACR")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.ACR, "RoleAssignment updated. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            if (GetModuleText().ToString() == "EZVisit")
            {
                GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.EZVisit, "RoleAssignment updated. EmployeeNo=" + employeeNO + "; CIL=" + employee.NameEN +
            "; Roles=" + roles + "; IsAdmin=" + isAdmin);
            }
            Entity_Changed(null, null);
        }

        protected override string GetEntityWhereExpression(string keyword)
        {
            string r = "(Count(select value r.RoleID from it.Roles as r where !r.Disabled and r.Description != '+pcat+' and r.Description != '+country+' and r.BelongsTo in {{{0}}} " + (this.admin.Checked ? " and (r.IsAdmin)" : "") + ") > 0 )";
            var filter = "";
            var sys = GetModuleName();
           
            if (!string.IsNullOrEmpty(keyword))
            {
                filter += "(it.NameEN like N'%" + keyword + "%'";
                string f=" or Count(select value r.RoleID from it.Roles as r where !r.Disabled and r.Description != '+pcat' and r.Description != '+country+' and r.BelongsTo in {{{0}}} and (r.Name like\"%" + keyword + "%\" or r.BelongsTo like\"%" + keyword + "%\"))>0) and ";
                filter += String.Format(f,String.Join(",",sys.Select(p=> "'"+p+"'").ToArray()));
                
            }
           
            filter += String.Format(r,
                String.Join(",", sys.Select(p => "'" + p + "'").ToArray()));

            return filter;
        }


        //TODO: remove logic code to BL
        private void InsertEmployee(EntityDataSourceChangingEventArgs e)
        {
            var user = e.Entity as Employee;
            string newEm = user.NameEN;
            //string newEm = e.Values["NameEN"].ToString();
            ////maybe empty em
            if (newEm == null) return;
            string chooseRolesStr;
            if (Request.Form["ChooseRoles"] == null) chooseRolesStr = string.Empty;
            else
                chooseRolesStr = Request.Form["ChooseRoles"].ToString();


            List<int> choseRoles = new List<int>();
            foreach (string rstr in chooseRolesStr.Split(','))
            {
                if (!string.IsNullOrEmpty(rstr))
                    choseRoles.Add(Convert.ToInt32(rstr));
            }
            RoleAssignmentHelper arh = new RoleAssignmentHelper();
            foreach (var sys in GetModuleName())
            {
                if (arh.SetUserRoles(newEm, choseRoles, sys, false) == false)
                {
                    ClientScript.RegisterClientScriptBlock(GetType(), "Role Assignment Failed", "<script>alert('" + Resources.Messages.RoleAssignmentFailed + "');</script>");
                    return;
                }
            }



            //添加该用户可访问ACR的project
            if (GetModuleName().Contains(SystemModule.ACR.ToString()) ||
                GetModuleName().Contains(SystemModule.Admin.ToString()))
                arh.CreateProjectMembers(newEm);

        }


        //TODO: remove logic code to BL
        private void UpdateEmployee(EntityDataSourceChangingEventArgs e)
        {
            var user = e.Entity as Employee;
            string emNo = user.EmployeeNo;
            if (emNo == null) throw new NullReferenceException("emNo");
            string chooseRolesStr;
            if (Request.Form["ChooseRoles"] == null) chooseRolesStr = string.Empty;
            else
                chooseRolesStr = Request.Form["ChooseRoles"].ToString();

            List<int> choseRoles = new List<int>();
            foreach (string rstr in chooseRolesStr.Split(','))
            {
                if (!string.IsNullOrEmpty(rstr))
                    choseRoles.Add(Convert.ToInt32(rstr));
            }
            RoleAssignmentHelper arh = new RoleAssignmentHelper();
            foreach (var sys in GetModuleName())
            {
                arh.SetUserRoles(emNo, choseRoles, sys, true);
            }


        }

        protected void edsRoles_Load(object sender, EventArgs e)
        {
            EntityDataSource eds = sender as EntityDataSource;
            eds.Where = String.Format(eds.Where,
                String.Join(",", GetModuleName().Select(p => "'" + p + "'").ToArray()));
        }

        //protected void edsIsadmin_Load(object sender, EventArgs e)
        //{
        //    EntityDataSource eds = sender as EntityDataSource;
        //    string admin=Request.Form["IsAdmin"];

        //    eds.Where = String.Format(eds.Where,
        //        String.Join(",", GetModuleName().Select(p => "'" + p + "'").ToArray()));
        //}
        /// <summary>
        /// 通过IsAdmin取yes/NO
        /// </summary>
        protected string GetIsAdmin(object isAdmin)
        {
            if (isAdmin == null)
                return "";
            if (Convert.ToBoolean(isAdmin) == true)
                return "Yes";
            if (Convert.ToBoolean(isAdmin) == false)
                return "No";
            return "";
        }


        protected void admin_CheckedChanged(object sender, EventArgs e)
        {
            //bool admin = ((CheckBox)sender).Checked;

            //if (admin == true)
            //{
            //    edsRoles.Where = "!it.Disabled and !it.IsAdmin  and it.Description != '+pcat+' and it.Description != '+country+' and  it.BelongsTo in {{{0}}}";
            //    gvMain.DataBind();
            //}
            //else
            //{
            //    edsRoles.Where = "it.Disabled";
            //    gvMain.DataBind();
            //}
        }


    }
}
